
<template>
  <div>
    <el-row class="samples-info-box">
      <el-col :span="12">
        <div class="grid-content bg-purple">
          <el-form ref="ruleForm2" :model="ruleForm2" :rules="rules2" label-width="100px" class="demo-ruleForm">
            <el-form-item label="组织机构" prop="deptName">
              <span>{{ deptName }}</span>
            </el-form-item>
            <el-form-item label="角色" prop="roleName">
              <span>{{ roleName }}</span>
            </el-form-item>
            <el-form-item label="真实姓名" prop="realName">
              <span>{{ realName }}</span>
            </el-form-item>
            <el-form-item label="用户名" prop="username">
              <el-input v-model="ruleForm2.username" type="text" :value="userInfo.username" disabled />
            </el-form-item>
            <el-form-item label="原密码" prop="password">
              <el-input v-model="ruleForm2.password" auto-complete="off" />
              <template slot="error" slot-scope="scope">
                <div class="sample-error-message">{{ scope.error }}</div>
              </template>
            </el-form-item>
            <el-form-item label="密码" prop="newpassword1">
              <el-input v-model="ruleForm2.newpassword1" auto-complete="off" />
              <template slot="error" slot-scope="scope">
                <div class="sample-error-message">{{ scope.error }}</div>
              </template>
            </el-form-item>
            <el-form-item label="确认密码" prop="newpassword2">
              <el-input v-model="ruleForm2.newpassword2" auto-complete="off" />
              <template slot="error" slot-scope="scope">
                <div class="sample-error-message">{{ scope.error }}</div>
              </template>
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="ruleForm2.phone" placeholder="验证码登录使用" />
            </el-form-item>
            <!-- <el-form-item label="头像">
              <my-upload v-model="show" field="file" :width="300" :height="300" url="/admin/user/upload" :headers="headers" img-format="png" @crop-upload-success="cropUploadSuccess" />
              <img :src="ruleForm2.avatar">
              <el-button type="primary" size="mini" @click="toggleShow">选择
                <i class="el-icon-upload el-icon--right" />
              </el-button>
            </el-form-item> -->
            <el-form-item>
              <el-button type="primary" @click="submitForm('ruleForm2')">提交</el-button>
              <el-button @click="resetForm('ruleForm2')">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import myUpload from 'vue-image-crop-upload'
import { getToken } from '@/utils/auth'
import { editInfo, getEditInfo } from '@/api/user'
import { setStore, getStore, removeStore } from '@/utils/store'
// import ElFormItem from "element-ui/packages/form/src/form-item.vue";

export default {
  components: {
    // ElFormItem,
    'my-upload': myUpload
  },
  data() {
    var validatePass = (rule, value, callback) => {
      if (this.ruleForm2.password !== '') {
        if (value === '') {
          callback(new Error('请输入密码'))
        } else if (value.length < 6) {
          callback(new Error('密码不能小于6位'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (this.ruleForm2.password !== '') {
        if (value === '') {
          callback(new Error('请再次输入密码'))
        } else if (value !== this.ruleForm2.newpassword1) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      realName: '',
      deptName: '',
      roleName: '',
      realName: '',
      userId: getStore({ name: 'userInfo' }).userId,
      fileList: [],
      show: false,
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      ruleForm2: {

        username: '',
        password: '',
        newpassword1: '',
        newpassword2: '',
        avatar: '',
        phone: ''
      },
      rules2: {
        password: [{ validator: validatePass, trigger: 'blur' }],
        newpassword1: [{ validator: validatePass, trigger: 'blur' }],
        newpassword2: [{ validator: validatePass2, trigger: 'blur' }]
      }
    }
  },
  created() {
    this.realName = this.userInfo.realName
    this.ruleForm2.username = this.userInfo.username
    this.realName = this.userInfo.realName
    this.ruleForm2.avatar = this.userInfo.avatar
    this.ruleForm2.phone = this.userInfo.phone
    this.getUserInfo(this.userId)
  },
  computed: {
    ...mapState({
      userInfo: state => state.user.userInfo
    })
  },
  methods: {
    getUserInfo(userId) {
      getEditInfo(userId)
        .then(res => {
          if (res.code === 1) {
            this.roleName = res.data.roleList[0].name
            this.deptName = res.data.deptName
          }
        })
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          editInfo(this.ruleForm2)
            .then(response => {
              // debugger
              if (response.code === 1) {
                this.userInfo.phone = this.ruleForm2.phone
                this.userInfo.avatar = this.ruleForm2.avatar
                this.$notify({
                  title: '成功',
                  message: '修改成功',
                  type: 'success',
                  duration: 2000
                })
                // 修改密码之后强制重新登录
                if (this.ruleForm2.newpassword1 !== '') {
                  this.$store.dispatch('user/FedLogOut').then(() => {
                    location.reload() // 为了重新实例化vue-router对象 避免bug
                  })
                } else {
                  this.$router.push({ path: '/' })
                }
              } else {
                this.$notify({
                  title: '失败',
                  message: response.msg,
                  type: 'error',
                  duration: 2000
                })
              }
            })
            .catch(() => {
              this.$notify({
                title: '失败',
                message: '系统错误，请联系管理员',
                type: 'error',
                duration: 2000
              })
            })
        } else {
          return false
        }
      })
    },
    resetForm(formName) {
      console.log(formName)
      this.$refs[formName].resetFields()
    },
    toggleShow() {
      this.show = !this.show
    },
    /**
     * upload success
     *
     * [param] jsonData   服务器返回数据，已进行json转码
     * [param] field
     */
    cropUploadSuccess(jsonData, field) {
      this.$store.commit('SET_AVATAR', jsonData.filename)
    }
  }
}
</script>
